package com.kclmedu.springsecuritydb.service;

import com.kclmedu.springsecuritydb.dao.UserDao;
import com.kclmedu.springsecuritydb.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
* @ProjectName:    自定义UserDetailsService实现类，目的是通过查询数据库来得到登录的用户
* @Package:        com.kclmedu.springsecuritydb.service
* @ClassName:      CustomUserDetailsService
* @Description:    
* @Author:         Teacher.YE
* @CreateDate:     2019/7/17 0:24
* @Version:        1.0.0  
*/
@Component(value = "customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    /************
     * 实现方法
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过userdao来查询用户名
        System.out.println("查询的用户名是："+username);
        //
        User userFromDb = userDao.findByUsername(username);
        //判断
        if(userFromDb == null) {
            //说明用户名在表中不存在，则必需抛出一个异常
            throw new UsernameNotFoundException("用户："+username+" 在数据库中不存在.");
        }
        //如果找到，则设置角色
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //使用简单角色[如果有多个角色的话，可以使用split切割后再循环生成
        String[] roles = userFromDb.getRole().split(",");
        //
        GrantedAuthority grantedAuthority = null;
        for(String role:roles) {
            grantedAuthority = new SimpleGrantedAuthority(role);
            //添加进集合中
            authorities.add(grantedAuthority);
        }
        //返回
        return new org.springframework.security.core.userdetails.User(
                                username,userFromDb.getPassword(),authorities);
    }
}
